package com.liwei.easyweibo.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.liwei.easyweibo.entity.Music;
import com.liwei.easyweibo.entity.Vedio;
import com.liwei.easyweibo.entity.WeiboContent;
import com.liwei.easyweibo.entity.WeiboItem;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

/**
 * 和Android相关的工具类
 * */
public class AndroidUtil {
	
	/*
	 *以最省内存的方式读取本地资源的图片 
	 * **/
	public static Bitmap readBitMap(Context context, String path) throws FileNotFoundException{
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inJustDecodeBounds = false;
		opt.inSampleSize 		= 10;   //width，hight设为原来的十分一
		
		return BitmapFactory.decodeFile(path, opt);
	}
	
	public static Bitmap getBitmapFromFile(String path, int width, int height) {
		File file = new File(path);
	    if (null != path && file.exists()) {
	        BitmapFactory.Options opts = null;
	        if (width > 0 && height > 0) {
	            opts = new BitmapFactory.Options();
	            opts.inJustDecodeBounds = true;
	            BitmapFactory.decodeFile(path, opts);
	            // 计算图片缩放比例
	            final int minSideLength = Math.min(width, height);
	            opts.inSampleSize = computeSampleSize(opts, minSideLength,
	                    width * height);
	            opts.inJustDecodeBounds = false;
	            opts.inInputShareable = true;
	            opts.inPurgeable = true;
	        }
	        try {
	            return BitmapFactory.decodeFile(path, opts);
	        } catch (OutOfMemoryError e) {
	            e.printStackTrace();
	        }
	    }
	    return null;
	}

	public static int computeSampleSize(BitmapFactory.Options options,
	        int minSideLength, int maxNumOfPixels) {
	    int initialSize = computeInitialSampleSize(options, minSideLength,
	            maxNumOfPixels);

	    int roundedSize;
	    if (initialSize <= 8) {
	        roundedSize = 1;
	        while (roundedSize < initialSize) {
	            roundedSize <<= 1;
	        }
	    } else {
	        roundedSize = (initialSize + 7) / 8 * 8;
	    }

	    return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options,
	        int minSideLength, int maxNumOfPixels) {
	    double w = options.outWidth;
	    double h = options.outHeight;

	    int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
	            .sqrt(w * h / maxNumOfPixels));
	    int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math
	            .floor(w / minSideLength), Math.floor(h / minSideLength));

	    if (upperBound < lowerBound) {
	        // return the larger one when there is no overlapping zone.
	        return lowerBound;
	    }

	    if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
	        return 1;
	    } else if (minSideLength == -1) {
	        return lowerBound;
	    } else {
	        return upperBound;
	    }
	}
	
	/**
	 * 从uri中得到文件的存储路径
	 * */
	public static String getFilePathFromUri(Context context, Uri uri){
		String[] proj = { MediaStore.Images.Media.DATA};
		Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
		
		int index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
		String path = "";
		if(index >=0){
			cursor.moveToFirst();
			path = cursor.getString(index);
		}
		return path;
	}
	
	/**
	 * 从文件存储路径得到URi
	 * 
	 * */
	public static Uri getImageContentUri(Context context, String filePath){
		Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
				new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA +"=? ", 
				new String[] { filePath }, null);
		Uri baseUri = null;
		int id = 0;
		if(cursor != null){
			cursor.moveToFirst();
			 id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
			
			 baseUri = Uri.parse("content://media/external/images/media");
		}
		return Uri.withAppendedPath(baseUri, String.valueOf(id));
	}
	
	public static WeiboContent parseFormJson(String str) throws Exception{
		JSONObject jsonObject = new JSONObject(str);
		JSONObject jsonObjectData = jsonObject.getJSONObject("data");
		WeiboContent content = new WeiboContent();
		content.setmHasNext(jsonObjectData.getInt("hasnext"));
		JSONArray jsonArray = jsonObjectData.getJSONArray("info");
		for(int i=0; i<jsonArray.length();i++){
			JSONObject jsonObjectArray = jsonArray.getJSONObject(i);
			WeiboItem item = fillDataToObject(jsonObjectArray);
			
			//转发微博的源内容
			if(! jsonObjectArray.isNull("source")){
				JSONObject jsonObjectSource = jsonObjectArray.getJSONObject("source");
				if(jsonObjectSource != null){
					WeiboItem item1= fillDataToObject(jsonObjectSource);
					item.setmWeiboItem(item1);
				}else{
					item.setmWeiboItem(null);
				}
			}
			
			content.addWeiboItem(item);
		}
		return content;
	}
	
	public static WeiboItem  fillDataToObject(JSONObject jsonObjectArray) throws Exception{
		WeiboItem item = new WeiboItem();
		
		item.setmCount(jsonObjectArray.getInt("count"));
		item.setmFrom(jsonObjectArray.getString("from"));
		item.setmFromUrl(jsonObjectArray.getString("fromurl"));
		item.setmWeiboId(jsonObjectArray.getString("id"));
		
		//图片列表
		if(! jsonObjectArray.isNull("image")){
			JSONArray jsonArrayImage = jsonObjectArray.getJSONArray("image");
			if(jsonArrayImage != null){
				List<String > imageList = null;
				for(int j=0; j<jsonArrayImage.length();j++){
					imageList = new ArrayList<String>();
					imageList.add(jsonArrayImage.getString(j));
				}
				item.setmImageUrlList(imageList);
			}else{
				item.setmImageUrlList(null);
			}
		}
		
		item.setmLatitude(jsonObjectArray.getLong("latitude"));
		item.setmLongitude(jsonObjectArray.getLong("longitude"));
		item.setmLocation(jsonObjectArray.getString("location"));
		item.setmMCount(jsonObjectArray.getInt("mcount"));
		
		//音乐
		if( ! jsonObjectArray.isNull("music")){
			JSONObject jsonObjectMusic = jsonObjectArray.getJSONObject("music");
			if(jsonObjectMusic != null){
				Music music = new Music();
				music.setmAuthor(jsonObjectMusic.getString("author"));
				music.setmTitle(jsonObjectMusic.getString("title"));
				music.setmUrl(jsonObjectMusic.getString("url"));
				item.setMusic(music);
			}else{
				item.setMusic(null);
			}
		}
		
		
		item.setmName(jsonObjectArray.getString("name"));
		item.setmNick(jsonObjectArray.getString("nick"));
		item.setmOpenid(jsonObjectArray.getString("openid"));
		item.setmOrigtext(jsonObjectArray.getString("origtext"));
		item.setmHead(jsonObjectArray.getString("head"));
		
		item.setmStatus(jsonObjectArray.getInt("status"));
		item.setmText(jsonObjectArray.getString("text"));
		item.setmTimeStamp(jsonObjectArray.getLong("timestamp"));
		item.setmType(jsonObjectArray.getInt("type"));
		
		//假如有视频的话
		if( !jsonObjectArray.isNull("video")){
			JSONObject jsonObjectVedio = jsonObjectArray.getJSONObject("video");
			if(jsonObjectVedio != null){
				Vedio vedio = new Vedio();
				vedio.setmPicUrl(jsonObjectVedio.getString("picurl"));
				vedio.setmPlayer(jsonObjectVedio.getString("player"));
				vedio.setmRealUrl(jsonObjectVedio.getString("realurl"));
				vedio.setmShortUrl(jsonObjectVedio.getString("shorturl"));
				vedio.setmTitle(jsonObjectVedio.getString("title "));
				item.setmVedio(vedio);
			}else{
				item.setmVedio(null);
			}
		}
		return item;
	}
	/**
	 * 返回内置sd卡路径,带后置分隔符
	 * 要获取下载目录, 请使用DownloadConfig.getDownloadPath
	 * 
	 * +yqm
	 * 这里返回的不一定是内置sd卡，看注释。应该理解为：首要保存用户数据的存储media/shared storage，即是ROM厂商希望
	 * 用户级的数据默认是存放这里。
	 * Traditionally this is an SD card, but it may also be implemented as
     * built-in storage in a device that is distinct from the protected
     * internal storage and can be mounted as a filesystem on a computer.
	 * @return
	 */
	public static String getPrimarySDCard() {
		// return Environment.getExternalStorageDirectory().getPath();
		String sdcardPath = Environment.getExternalStorageDirectory().getPath();
		if (null != sdcardPath && !sdcardPath.endsWith("/")) {
			sdcardPath = sdcardPath + "/";
		}
		return sdcardPath;
	}
	
}
